//
//  StatusListViewModel.swift
//  JJWeibo
//
//  Created by JJ on 15/9/6.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import ReactiveCocoa
import SDWebImage

class StatusListViewModel: NSObject {
    
   lazy var status: [StatusViewModel] = [StatusViewModel]()
    
    func loadStatus(isPullRefresh isPullRefresh:Bool)->RACSignal{
        
        var since_id = status.first?.status.id ?? 0
        var max_id=0
        
        if isPullRefresh{
            
            since_id=0
            max_id=status.last?.status.id ?? 0
        }
        
      return RACSignal.createSignal({ [weak self](subscriber) -> RACDisposable! in
       
        StatusDAL.loadStatus(since_id, max_id: max_id, complete: { (array) -> () in
            
            // 1. 获取 result 中的 statuses 字典数组
            if array == nil {
                printLog("没有正确的数据")
                subscriber.sendError(NSError(domain: "com.itheima.error", code: -1002, userInfo: ["error message": "没有正确数据"]))
                return
            }
            // 2. 字典转模型
            // 定义并且创建一个临时数组，记录当前网络请求返回的结果
            var arrayM = [StatusViewModel]()
            
            // 遍历数组，字典转模型
            for dict in array! {
                arrayM.append(StatusViewModel(status: Status(dic: dict)))
            }
            
            
            // 添加尾随闭包
            self?.cacheWebImage(arrayM) {
                
                if max_id > 0 {     // 将新数据拼接在现有数组的末尾
                    self?.status += arrayM
                } else {            // 初始刷新&下拉刷新
                    self?.status = arrayM + self!.status
                }
                
                // 如果是下拉刷新，提示用户
                if since_id > 0 {
                    // RAC 是 OC 的，通知订阅者，下拉刷新的数据
                    subscriber.sendNext(arrayM.count)
                }
                
                // 3. 通知调用方数据加载完成
                subscriber.sendCompleted()
            }
        })
        return nil
        })
    }
    
    private func cacheWebImage(array:[StatusViewModel],finish:()->()){
        
        let group=dispatch_group_create()
        
        
        for viewModel in array{
            
            let count=viewModel.thumbnailURLs?.count ?? 0
            
            if count != 1 {
                continue
            }
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(viewModel.thumbnailURLs![0], options: [], progress: nil, completed: { (image, _, _, _, _) -> Void in
                
                dispatch_group_leave(group)
            })
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finish()
        }
        
    }
    

}








